<?php
namespace Api\Controller;
/**
 * 棋牌室
 */
class ShopController extends ApiController
{
    protected $noCheck = ['detail_img', 'types'];

    function _initialize() {
        parent::_initialize();
    }

    public function types()
    {
        $list = M('ShopType')->where(['status'=>1])->order('sort desc,id asc')->field('id,type_name as name,color')->select();
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'list'=>$list]);
    }

    public function detail_img()
    {
        $img_1 = yzl_config('store.detail_img_1');
        $img_2 = yzl_config('store.detail_img_2');
        $img_3 = yzl_config('store.detail_img_3');
        $img_4 = yzl_config('store.detail_img_4');
        $img_5 = yzl_config('store.detail_img_5');
        $imgs = [
            'img_1' => $img_1,
            'img_2' => $img_2,
            'img_3' => $img_3,
            'img_4' => $img_4,
            'img_5' => $img_5,
        ];
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'imgs'=>$imgs]);
    }

    public function upload()
    {
        $key = I('key');
        $watermark = I('watermark');
        $watermark = $watermark==2 ? false : true;
        $upload = $this->uploadimgsy($key, $watermark);
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'upload'=>$upload]);
    }

    /**
     * 商家信息
     */
    public function shop_info()
    {
        $shop = M('shop')->where(['uid|phone|tel'=>[$this->uid, $this->user['phone'], $this->user['phone'], '_multi'=>ture], 'status'=>1])->find();
        if(empty($shop)){
            $this->ajaxReturn(['s' => false, 'm' => '您还不是商家。']);
        }
        $hd_tpls = M('shop_activity_tpls')->where(['status'=>1])->order('sort desc')->field('id,img')->select();
        !$hd_tpls && $hd_tpls = [];
        // 商家模板
        if($shop['activity_tpl']){
            $shopTpl = M('shop_activity_tpls')->where(['id'=>$shop['activity_tpl']])->field('id,img')->find();
            if($shopTpl){
                $shopTpl['desc'] = $shop['activity_desc'];
            }
        }
        $coupons = M('shop_coupons')->alias('sc')
        ->join('__SHOP_COUPON_TPLS__ t ON sc.tpl_id=t.id', 'left')
        ->where(['sc.shop_id'=>$shop['id']])
        ->field('sc.id,sc.title,sc.tpl_id,sc.is_condition,sc.condition_amount,sc.discount_amount,sc.get_start_time,sc.get_end_time,sc.use_start_time,sc.use_end_time,sc.create_time,t.img')
        ->select();
        if($coupons){
            foreach ($coupons as $key => &$coupon) {
                $coupon['get_start_time'] = date('Y-m-d', $coupon['get_start_time']);
                $coupon['get_end_time'] = date('Y-m-d', $coupon['get_end_time']);
                $coupon['use_start_time'] = date('Y-m-d', $coupon['use_start_time']);
                $coupon['use_end_time'] = date('Y-m-d', $coupon['use_end_time']);
                $coupon['create_time'] = date('Y-m-d H:i:s', $coupon['create_time']);
                $coupon['condition_amount'] = $coupon['condition_amount']*1;
                $coupon['discount_amount'] = $coupon['discount_amount']*1;
            }
        }
        $coupon_tpls = M('shop_coupon_tpls')->where(['status'=>1])->order('sort desc')->field('id,img')->select();
        !$coupon_tpls && $coupon_tpls = [];
        $technician = M('shop_technician')->where(['shop_id'=>$shop['id']])->field('id,serial_number,img,title,desc')->select();
        !$technician && $technician = [];
        $info = [
            'is_discount_today' => $shop['is_discount_today'],
            'ds'            => $shop['ds'],
            'shop'          => $shop,
            'activity'      => $shopTpl,
            'hd_tpls'       => $hd_tpls,
            'coupons'       => $coupons,
            'coupon_tpls'   => $coupon_tpls,
            'technician'    => $technician,
        ];
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'info'=>$info]);
    }

    public function technician_info()
    {
        $technician_id = I('technician_id');
        $technician = M('shop_technician')->where(['id'=>$technician_id])->field('id,serial_number,img,title,desc,sf_like,tx_like,rq_like,rr_like,jj_like,like_num')->find();
        if(empty($technician)){
            $this->ajaxReturn(['s' => false, 'm' => '不存在或已被删除']);
        }
        $like_log = M('shop_technician_like_log')
        ->where(['technician_id'=>$technician_id, 'user_id'=>$this->uid])
        ->field('like_type')
        ->group('like_type')
        ->select();
        $like_log = $like_log ? array_column($like_log, 'like_type'):[];
        $technician['is_sf_like'] = in_array('sf_like', $like_log) ? 1 : 0;
        $technician['is_tx_like'] = in_array('tx_like', $like_log) ? 1 : 0;
        $technician['is_rq_like'] = in_array('rq_like', $like_log) ? 1 : 0;
        $technician['is_rr_like'] = in_array('rr_like', $like_log) ? 1 : 0;
        $technician['is_jj_like'] = in_array('jj_like', $like_log) ? 1 : 0;
        $technician['is_like_num'] = in_array('like_num', $like_log) ? 1 : 0;
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'technician'=>$technician]);
    }

    public function get_coupon()
    {
        $coupon_id = I('coupon_id');
        $has = M('user_coupons')->where(['user_id'=>$this->uid, 'coupon_id'=>$coupon_id])->find();
        if($has){
            $this->ajaxReturn(['s' => false, 'm' => '您已领取']);
        }
        $coupon = M('shop_coupons')->where(['id'=>$coupon_id])->find();
        if(empty($coupon)){
            $this->ajaxReturn(['s' => false, 'm' => '优惠券不存在或已被删除']);
        }
        $couponData = [
            'coupon_id' => $coupon_id,
            'user_id'   => $this->uid,
            'shop_id'   => $coupon['shop_id'],
            'tpl_id'   => $coupon['tpl_id'],
            'title' => $coupon['title'],
            'is_condition' => $coupon['is_condition'],
            'condition_amount' => $coupon['condition_amount'],
            'discount_amount' => $coupon['discount_amount'],
            'use_start_time' => $coupon['use_start_time'],
            'use_end_time' => $coupon['use_end_time'],
            'is_use'   => 0,
            'use_time' => 0,
            'create_time'   => time(),
            'update_time'   => time(),
        ];
        M('user_coupons')->add($couponData);
        $this->ajaxReturn(['s' => true, 'm' => '领取成功']);
    }

    public function coupon_users()
    {
        $shops = M('shop')
        ->where(['uid|phone|tel'=>[$this->uid, $this->user['phone'], $this->user['phone'], '_multi'=>ture], 'status'=>1])
        ->field('id')
        ->select();
        $shop_ids = $shops ? array_column($shops, 'id') : [];
        $coupon_users = [];
        if($shop_ids){
            $coupon_users = M('UserCoupons')->alias('uc')
            ->join('__SHOP__ s ON s.id=uc.shop_id', 'LEFT')
            ->join('__USER__ u ON u.id=uc.user_id', 'LEFT')
            ->join('__MEMBER_NO__ mn ON uc.user_id=mn.user_id', 'left')
            ->where(['uc.shop_id'=>['in', $shop_ids]])
            ->order('uc.id desc')
            ->field('uc.id,uc.user_id,u.nickname,u.img as avatar,u.is_nearby,mn.member_no,uc.title,uc.is_use,uc.is_condition,uc.condition_amount,uc.discount_amount,uc.use_start_time,uc.use_end_time,uc.create_time')
            ->select();
            if($coupon_users){
                foreach ($coupon_users as $key => &$coupon) {
                    if($coupon['is_use']){
                        $status = 3;// 已使用
                        $status_desc = "已使用";
                    }else{
                        if($now_time < $coupon['use_start_time']){
                            $status = 1;// 未到可使用时间
                            $status_desc = "未到可以使用时间";
                        }else if($now_time > $coupon['use_end_time']){
                            $status = 4;// 过期
                            $status_desc = "已过期";
                        }else{
                            $status = 2;// 可用
                            $status_desc = "未使用";
                        }
                    }
                    $coupon['condition_amount'] = $coupon['condition_amount']*1;
                    $coupon['discount_amount'] = $coupon['discount_amount']*1;
                    $coupon['status'] = $status;
                    $coupon['status_desc'] = $status_desc;
                    $coupon['use_start_time'] = date('Y-m-d', $coupon['use_start_time']);
                    $coupon['use_end_time'] = date('Y-m-d', $coupon['use_end_time']);
                    $coupon['create_time'] = date('Y-m-d H:i:s', $coupon['create_time']);
                    $coupon['title'] = "满{$coupon['condition_amount']}元减{$coupon['discount_amount']}元 ";
                    $coupon['title'].=$coupon['use_start_time']==$coupon['use_end_time'] ? $coupon['use_start_time'] : $coupon['use_start_time'].'至'.$coupon['use_end_time'];
                }
            }
        }
        $this->ajaxReturn(['s' => true, 'm' => 'ok', 'list'=>$coupon_users]);
    }

    /**
     * 删除单个用户优惠券
     */
    public function coupon_user_del()
    {
        $id = I('id');
        $userCoupon = M('UserCoupons')->where(['id'=>$id])->find();
        if(empty($userCoupon)){
            $this->ajaxReturn(['s' => false, 'm' => '不存在或已被删除']);
        }
        $shop = M('shop')->where(['id'=>$userCoupon['shop_id']])->find();
        if(empty($shop)){
            $this->ajaxReturn(['s' => false, 'm' => '优惠券店铺已不存在，无权限删除']);
        }
        if(($this->uid && $shop['uid'] == $this->uid) || ($this->user && ($shop['phone'] == $this->user['phone'] || $shop['tel'] == $this->user['phone']))){
        }else{
            $this->ajaxReturn(['s' => false, 'm' => '非您的店铺发布的优惠券，无权限删除']);
        }
        $res = M('UserCoupons')->where(['id'=>$id])->delete();
        if($res!==false){
            $this->ajaxReturn(['s' => true, 'm' => '删除成功']);
        }else{
            $this->ajaxReturn(['s' => false, 'm' => '删除失败']);
        }
    }

    /**
     * 删除所有领取的优惠券
     */
    public function coupon_user_del_all()
    {
        $shops = M('shop')
        ->where(['uid|phone|tel'=>[$this->uid, $this->user['phone'], $this->user['phone'], '_multi'=>ture], 'status'=>1])
        ->field('id')
        ->select();
        $shop_ids = $shops ? array_column($shops, 'id') : [];
        if(empty($shop_ids)){
            $this->ajaxReturn(['s' => false, 'm' => '您还不是商家']);
        }
        $res = M('UserCoupons')->where(['shop_id'=>['in', $shop_ids]])->delete();
        if($res!==false){
            $this->ajaxReturn(['s' => true, 'm' => '删除成功']);
        }else{
            $this->ajaxReturn(['s' => false, 'm' => '删除失败']);
        }
    }

    public function shop_edit()
    {
        $id = I('id');
        $jishiselect_1 = I('jishiselect_1', '-1');
        $jishiselect_2 = I('jishiselect_2', '-1');
        $jishiselect_3 = I('jishiselect_3', '-1');
        $coupons = I('coupons');
        $activity = I('activity');
        $technicians = I('technicians');
        $jishiselect_1 !=-1 && $jishiselect_1 = $jishiselect_1 ? 1 : 0;
        $jishiselect_2 !=-1 && $jishiselect_2 = $jishiselect_2 ? 1 : 0;
        $jishiselect_3 !=-1 && $jishiselect_3 = $jishiselect_3 ? 1 : 0;

        $shopInfo = M('shop')->where(['id'=>$id])->find();
        if(empty($shopInfo)){
            $this->ajaxReturn(['s'=>false, 'm'=>'店铺不存在']);
        }
        if(($this->uid && $shopInfo['uid']==$this->uid) || ($this->user && ($shopInfo['phone'] == $this->user['phone'] || $shopInfo['tel'] == $this->user['phone']))){
        }else{
            $this->ajaxReturn(['s'=>false, 'm'=>'不是您的所在店铺，无法编辑。']);
        }
        // 活动验证
        
        // 优惠券验证
        if($coupons){
            foreach ($coupons as $key => &$coupon) {
                if(isset($coupon['id'])){
                    $couponHas = M('shop_coupons')->where(['id'=>$coupon['id']])->find();
                    if(empty($couponHas) || $couponHas['shop_id']!=$id){
                        $this->ajaxReturn(['s'=>false, 'm'=>'优惠券错误']);
                    }
                }
                $coupon['get_start_time'] = strtotime($coupon['get_start_time']);
                $coupon['get_end_time'] = strtotime($coupon['get_end_time']);
                $coupon['use_start_time'] = strtotime($coupon['use_start_time']);
                $coupon['use_end_time'] = strtotime($coupon['use_end_time']);
                if(empty($coupon['get_start_time']) || empty($coupon['get_end_time']) || empty($coupon['use_start_time']) || empty($coupon['use_end_time'])){
                    $this->ajaxReturn(['s'=>false, 'm'=>'优惠券日期格式错误，请选择正确的日期']);
                }
                $coupon['get_start_time'] = strtotime(date('Y-m-d', $coupon['get_start_time']));
                $coupon['get_end_time'] = strtotime(date('Y-m-d', $coupon['get_end_time'])." 23:59:59");
                $coupon['use_start_time'] = strtotime(date('Y-m-d', $coupon['use_start_time']));
                $coupon['use_end_time'] = strtotime(date('Y-m-d', $coupon['use_end_time'])." 23:59:59");
                if($coupon['get_end_time'] <= $coupon['get_start_time']){
                    $this->ajaxReturn(['s'=>false, 'm'=>'领取结束时间必须大于领取开始时间']);
                }
                if($coupon['use_end_time'] <= $coupon['use_start_time']){
                    $this->ajaxReturn(['s'=>false, 'm'=>'可使用结束时间必须大于可使用开始时间']);
                }
                if($coupon['use_start_time'] < $coupon['get_start_time']){
                    $this->ajaxReturn(['s'=>false, 'm'=>'可使用开始时间不能小于领取开始时间']);
                }
                if($coupon['use_end_time'] < $coupon['use_start_time']){
                    $this->ajaxReturn(['s'=>false, 'm'=>'可使用结束时间不能小于领取结束时间']);
                }
                if(!isset($coupon['condition_amount'])){
                    $this->ajaxReturn(['s'=>false, 'm'=>'提交失败，优惠券数据错误']);
                }
                if(!isset($coupon['discount_amount'])){
                    $this->ajaxReturn(['s'=>false, 'm'=>'提交失败，优惠券数据错误']);
                }
                if(!isset($coupon['tpl_id'])){
                    $this->ajaxReturn(['s'=>false, 'm'=>'提交失败，优惠券数据错误']);
                }
                if(!isset($coupon['title'])){
                    $this->ajaxReturn(['s'=>false, 'm'=>'提交失败，优惠券数据错误']);
                }
                if($coupon['condition_amount']){
                    $coupon['is_condition'] = 1;
                }else{
                    $coupon['is_condition'] = 0;
                }
            }
        }
        // 技师验证
        if($technicians){
            foreach ($technicians as $key => $technician) {
                if(isset($technician['id'])){
                    $technicianHas = M('shop_technician')->where(['id'=>$technician['id']])->find();
                    if(empty($technicianHas) || $technicianHas['shop_id']!=$id){
                        $this->ajaxReturn(['s'=>false, 'm'=>'技师错误']);
                    }
                }
            }
        }
        
        $is_discount_today = I('is_discount_today', 0);
        $ds = I('ds');

        $activity_tpl = $activity && !empty($activity['activity_tpl']) ? $activity['activity_tpl'] : '';
        $activity_desc = $activity && !empty($activity['activity_desc']) ? $activity['activity_desc'] : '';
        $shop_update = [
            'is_discount_today' => $is_discount_today,
            'ds'                => $ds,
            'activity_tpl'      => $activity_tpl,
            'activity_desc'     => $activity_desc,
        ];
        if($jishiselect_1!=-1){
            $shop_update['jishiselect_1'] = $jishiselect_1;
        }
        if($jishiselect_2!=-1){
            $shop_update['jishiselect_2'] = $jishiselect_2;
        }
        if($jishiselect_3!=-1){
            $shop_update['jishiselect_3'] = $jishiselect_3;
        }
        M()->startTrans();
        $res = M('shop')->where(['id'=>$id])->save($shop_update);
        // 优惠券
        if($coupons){
            $coupon_ids = [];
            foreach ($coupons as $key => $coupon2) {
                $couponData = [
                    'tpl_id'            => $coupon2['tpl_id'],
                    'title'             => $coupon2['title'],
                    'is_condition'      => $coupon2['is_condition'],
                    'condition_amount'  => $coupon2['condition_amount'],
                    'discount_amount'   => $coupon2['discount_amount'],
                    'get_start_time'    => $coupon2['get_start_time'],
                    'get_end_time'      => $coupon2['get_end_time'],
                    'use_start_time'    => $coupon2['use_start_time'],
                    'use_end_time'      => $coupon2['use_end_time'],
                    'update_time'       => time(),
                ];
                if(isset($coupon2['id'])){
                    $coupon_id = $coupon2['id'];
                    M('shop_coupons')->where(['id'=>$coupon2['id']])->save($couponData);
                }else{
                    $couponData['shop_id'] = $id;
                    $couponData['user_id'] = $this->uid;
                    $couponData['create_time'] = time();
                    $coupon_id = M('shop_coupons')->add($couponData);
                }
                $coupon_ids[] = $coupon_id;
                if(!$coupon_id){
                    M()->rollback();
                    $this->ajaxReturn(['s'=>false, 'm'=>'提交失败']);
                }
            }
            M('shop_coupons')->where(['shop_id'=>$id, 'id'=>['not in', $coupon_ids]])->delete();
        }else{
            M('shop_coupons')->where(['shop_id'=>$id])->delete();
        }
        // 技师
        if($technicians){
            $technician_ids = [];
            foreach ($technicians as $key => $technician) {
                $technicianData = [
                    'title'  => $technician['title'],
                    'desc' => $technician['desc'],
                    'img' => $technician['img'],
                    'serial_number' => $technician['serial_number'],
                    'update_time' => time(),
                ];
                if(isset($technician['id'])){
                    $technician_id = $technician['id'];
                    M('shop_technician')->where(['id'=>$technician['id']])->save($technicianData);
                }else{
                    $technicianData['shop_id'] = $id;
                    $technicianData['user_id'] = $this->uid;
                    $technicianData['create_time'] = time();
                    $technician_id = M('shop_technician')->add($technicianData);
                }
                $technician_ids[] = $technician_id;
                if(!$technician_id){
                    M()->rollback();
                    $this->ajaxReturn(['s'=>false, 'm'=>'提交失败']);
                }
            }
            M('shop_technician')->where(['shop_id'=>$id, 'id'=>['not in', $technician_ids]])->delete();
        }else{
            M('shop_technician')->where(['shop_id'=>$id])->delete();
        }
        M()->commit();

        if($res!==false){
            $this->ajaxReturn(['s'=>true, 'm'=>'修改成功']);
        }else{
            $this->ajaxReturn(['s'=>false, 'm'=>'修改失败']);
        }
    }

    /**
     * 技师点赞
     */
    public function technician_like()
    {
        $technician_id  = I('technician_id');
        $type = I('type');
        if(!in_array($type, ['like_num', 'sf_like', 'tx_like', 'rq_like', 'rr_like', 'jj_like'])){
            $this->ajaxReturn(['s'=>false, 'm'=>'参数错误']);
        }
        $technician = M('shop_technician')->where(['id'=>$technician_id])->find();
        if(empty($technician)){
            $this->ajaxReturn(['s'=>false, 'm'=>'技师不存在或已被删除']);   
        }
        $has = M('shop_technician_like_log')
        ->where(['technician_id'=>$technician_id, 'user_id'=>$this->uid, 'like_type'=>$type])
        ->find();
        if($has){
            $this->ajaxReturn(['s'=>false, 'm'=>'您已点过']);
        }
        M('shop_technician_like_log')->add([
            'technician_id' => $technician_id,
            'user_id'       => $this->uid,
            'like_type'     => $type,
            'create_time'   => time(),
        ]);
        M('shop_technician')->where(['id'=>$technician_id])->setInc($type, 1);
        $this->ajaxReturn(['s'=>true, 'm'=>'ok']);
    }

    /**
     * 点赞
     */
    public function like()
    {
        $id = I('id');
        $res = like_log($this->uid, 2, $id);
        if($res['status']){
            $this->ajaxReturn(['s'=>true, 'm'=>'点赞成功']);
        }else{
            $this->ajaxReturn(['s'=>false, 'm'=>$res['msg']]);
        }

        $id = I('id');
        $info = M('shop')->where(['id'=>$id])->find();
        if(empty($info)){
            $this->ajaxReturn(['s'=>false, 'm'=>'门店不存在']);
        }
        $res = M('shop')->where(['id'=>$id])->setInc('like_num', 1);
        if($res){
            $this->ajaxReturn(['s'=>true, 'm'=>'点赞成功']);
        }else{
            $this->ajaxReturn(['s'=>false, 'm'=>'点赞失败']);
        }
    }

    /**
     * 员工
     * @return void
     */
    public function staff() {
        $page = I('page');
        $shop_id = I('shop_id');

        $shopInfo = M('shop')->where(['id'=>$shop_id])->find();
        if(empty($shopInfo)){
            $this->ajaxReturn(['s'=>false, 'm'=>'棋牌室不存在']);
        }
        $can_edit = 0;
        if(($this->uid && $shopInfo['uid']==$this->uid) || ($this->user && ($shopInfo['phone'] == $this->user['phone'] || $shopInfo['tel'] == $this->user['phone']))){
            $can_edit = 1;
        }
        $map = ['shop_id'=>$shop_id];
        if($page){
            $data_list = D('Api/ShopStaff')->where($map)->page($page, 20)->field('id,user_name,phone,address,position,role')->order('role desc,id asc')->select();
        }else{
            $data_list = D('Api/ShopStaff')->where($map)->field('id,user_name,phone,address,position,role')->order('role desc,id asc')->select();
        }
        // if($data_list){
        //     // 职位
        //     $position = yzl_config('shop_glrj.shop_glrj_staff_position');
        //     foreach ($data_list as $key => &$row) {
        //         unset($row['role']);
        //         // $row['position'] = isset($position[$row['position']]) ? $position[$row['position']] : '';
        //     }
        // }
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'list'=>$data_list, 'can_edit'=>$can_edit]);
    }

    /**
     * 员工编辑需要的配置数据
     * @return void
     */
    public function staff_config() {
        // 职位
        $position = yzl_config('shop_glrj.shop_glrj_staff_position');
        // 性别
        $sex = yzl_config('shop_glrj.shop_glrj_sex');
        // 学历
        $education = yzl_config('shop_glrj.shop_glrj_staff_education');
        // 角色
        $roles = yzl_config('shop_glrj.shop_glrj_staff_role');
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'position'=>$position, 'sex'=>$sex, 'education'=>$education, 'roles'=>$roles]);
    }
    
    public function staff_add() {
        $data = I('post.');
        $wages = I('wages/a', []);
        $emergency_1 = I('emergency_1');
        $emergency_2 = I('emergency_2');
        $data['wages'] = json_encode($wages);
        $data['emergency_contact'] = $emergency_1.','.$emergency_2;
        $data['user_id'] = $this->uid;
        $this->check_edit_glrj($data['shop_id']);
        $model = D('Api/ShopStaff');
        if($model->create($data)){
            $insertId = $model->add(); // 写入数据到数据库
            if ($insertId) {
                $this->ajaxReturn(['s'=>true, 'm'=>'提交成功']);
            }else{
                $this->ajaxReturn(['s'=>false, 'm'=>'提交失败']);
            }
        }else{
            $this->ajaxReturn(['s'=>false, 'm'=>$model->getError()]);
        }
    }

    /**
     * 员工信息
     * @return void
     */
    public function staff_info() {
        $id = I('id');
        $shop_id = I('shop_id');
        
        $model = D('Api/ShopStaff');
        $info = $model->where(['id'=>$id])->find();
        if(empty($info) || $info['shop_id'] != $shop_id){
            $this->ajaxReturn(['s'=>false, 'm'=>"信息不存在"]);
        }
        $info['wages'] = empty($info['wages']) ? [] : json_decode($info['wages'], true);
        $contact = explode(',', $info['emergency_contact']);
        $info['emergency_1'] = isset($contact[0]) ? $contact[0] : '';
        $info['emergency_2'] = isset($contact[1]) ? $contact[1] : '';
        // 职位
        $position = yzl_config('shop_glrj.shop_glrj_staff_position');
        // 性别
        $sex = yzl_config('shop_glrj.shop_glrj_sex');
        // 学历
        $education = yzl_config('shop_glrj.shop_glrj_staff_education');
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'info'=>$info, 'position'=>$position, 'sex'=>$sex, 'education'=>$education]);
    }

    public function staff_edit() {
        $id = I('id');
        $data = I('post.');
        $wages = I('wages/a', []);
        $emergency_1 = I('emergency_1');
        $emergency_2 = I('emergency_2');
        $data['wages'] = json_encode($wages);
        $data['emergency_contact'] = $emergency_1.','.$emergency_2;
        $data['user_id'] = $this->uid;
        $this->check_edit_glrj($data['shop_id']);
        $model = D('Api/ShopStaff');
        if($model->create($data)){
            $res = $model->where(['id'=>$id, 'user_id'=>$this->uid])->save();
            if($res){
                $this->ajaxReturn(['s'=>true, 'm'=>'修改成功']);
            }else{
                $this->ajaxReturn(['s'=>false, 'm'=>'修改失败']);
            }
        }else{
            $this->ajaxReturn(['s'=>false, 'm'=>$model->getError()]);
        }
    }

    /**
     * 员工删除
     * @return void
     */
    public function staff_del() {
        $ids = I('ids');
        $shop_id = I('shop_id');
        if(empty($ids)){
            $this->ajaxReturn(['s'=>false, 'm'=>'请选择删除项']);
        }
        $this->check_edit_glrj($shop_id);
        $res = D('Api/ShopStaff')->where(['id'=>['in', $ids], 'shop_id'=>$shop_id])->delete();
        if($res!==false){
            $this->ajaxReturn(['s'=>true, 'm'=>'删除成功']);
        }else{
            $this->ajaxReturn(['s'=>false, 'm'=>'删除失败']);
        }
    }

    /**
     * 客户列表
     * @return void
     */
    public function customer() {
        $page = I('page');
        $shop_id = I('shop_id');

        $shopInfo = M('shop')->where(['id'=>$shop_id])->find();
        if(empty($shopInfo)){
            $this->ajaxReturn(['s'=>false, 'm'=>'棋牌室不存在']);
        }
        $can_edit = 0;
        if(($this->uid && $shopInfo['uid']==$this->uid) || ($this->user && ($shopInfo['phone'] == $this->user['phone'] || $shopInfo['tel'] == $this->user['phone']))){
            $can_edit = 1;
        }

        $model = D('Api/ShopCustomer');
        if($page){
            $data_list = $model->where(['shop_id'=>$shop_id])->page($page, 20)->field('id,customer_name,phone,address')->select();
        }else{
            $data_list = $model->where(['shop_id'=>$shop_id])->field('id,customer_name,phone,address')->select();
        }
        // if($data_list){
        //     foreach ($data_list as $key => &$row) {
        //     }
        // }
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'list'=>$data_list, 'can_edit'=>$can_edit]);
    }
    
    /**
     * 添加客户
     * @return void
     */
    public function customer_add(){
        $data = I('post.');
        $goods = I('goods/a', []);
        $data['goods'] = json_encode($goods);
        $data['user_id'] = $this->uid;
        $this->check_edit_glrj($data['shop_id']);
        $model = D('Api/ShopCustomer');
        if($model->create($data)){
            $insertId = $model->add();
            if($insertId){
                $this->ajaxReturn(['s'=>true, 'm'=>'添加成功']);
            }else{
                $this->ajaxReturn(['s'=>false, 'm'=>'添加失败']);
            }
        }else{
            $this->ajaxReturn(['s'=>false, 'm'=>$model->getError()]);
        }
    }

    /**
     * 获取客户信息
     * @return void
     */
    public function customer_info(){
        $id = I('id');
        $shop_id = I('shop_id');

        $info = D('Api/ShopCustomer')->where(['id'=>$id])->find();
        if(empty($info) || $info['shop_id'] != $shop_id){
            $this->ajaxReturn(['s'=>false, 'm'=>'信息不存在']);
        }
        $info['goods'] = empty($info['goods']) ? [] : json_decode($info['goods'], true);
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'info'=>$info]);
    }

    /**
     * 编辑客户
     * @return void
     */
    public function customer_edit(){
        $id = I('id');
        $data = I('post.');
        $goods = I('goods/a', []);
        $data['goods'] = json_encode($goods);
        $this->check_edit_glrj($data['shop_id']);
        $model = D('Api/ShopCustomer');
        if($model->create($data)){
            $res = $model->where(['id'=>$id, 'user_id'=>$this->uid])->save();
            if($res !== false){
                $this->ajaxReturn(['s'=>true, 'm'=>'修改成功']);
            }else{
                $this->ajaxReturn(['s'=>false, 'm'=>'修改失败']);
            }
        }else{
            $this->ajaxReturn(['s'=>false, 'm'=>$model->getError()]);
        }
    }

    /**
     * 删除客户
     * @return void
     */
    public function customer_del(){
        $ids = I('ids');
        $shop_id = I('shop_id');
        if(empty($ids)){
            $this->ajaxReturn(['s'=>false, 'm'=>'请选择删除项']);
        }
        $this->check_edit_glrj($shop_id);
        $res = D('Api/ShopCustomer')->where(['id'=>['in', $ids], 'shop_id'=>$shop_id])->delete();
        if($res!==false){
            $this->ajaxReturn(['s'=>true, 'm'=>'删除成功']);
        }else{
            $this->ajaxReturn(['s'=>false, 'm'=>'删除失败']);
        }
    }

    /**
     * 年度报表
     * @return void
     */
    public function annual_report() {
        $page = I('page');
        $shop_id = I('shop_id');

        $shopInfo = M('shop')->where(['id'=>$shop_id])->find();
        if(empty($shopInfo)){
            $this->ajaxReturn(['s'=>false, 'm'=>'棋牌室不存在']);
        }
        $can_edit = 0;
        if(($this->uid && $shopInfo['uid']==$this->uid) || ($this->user && ($shopInfo['phone'] == $this->user['phone'] || $shopInfo['tel'] == $this->user['phone']))){
            $can_edit = 1;
        }

        $model = D('Api/ShopSales');
        if($page){
            $list = $model->where(['shop_id'=>$shop_id])->page($page, 20)->order('id desc')->field('id,month_sales,month_total_sales')->select();
        }else{
            $list = $model->where(['shop_id'=>$shop_id])->order('id desc')->field('id,month_sales,month_total_sales')->select();
        }
        // if($list){
        //     foreach ($list as $key => &$row) {
        //     }
        // }
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'list'=>$list, 'can_edit'=>$can_edit]);
    }
    /**
     * 添加年度报表
     * @return void
     */
    public function report_add(){
        $data = I('post.');
        $daily_sales = I('daily_sales/a', []);
        $data['user_id'] = $this->uid;
        $data['daily_sales'] = json_encode($daily_sales);
        $this->check_edit_glrj($data['shop_id']);
        $model = D('Api/ShopSales');
        if($model->create($data)){
            $insertId = $model->add();
            if($insertId){
                $this->ajaxReturn(['s'=>true, 'm'=>'添加成功']);
            }else{
                $this->ajaxReturn(['s'=>false, 'm'=>'添加失败']);
            }
        }else{
            $this->ajaxReturn(['s'=>false, 'm'=>$model->getError()]);
        }
    }

    /**
     * 获取年度报表信息
     * @return void
     */
    public function report_info(){
        $id = I('id');
        $shop_id = I('shop_id');

        $info = D('Api/ShopSales')->where(['id'=>$id])->find();
        if(empty($info) || $info['shop_id'] != $shop_id){
            $this->ajaxReturn(['s'=>false, 'm'=>'信息不存在']);
        }
        $info['daily_sales'] = empty($info['daily_sales']) ? [] : json_decode($info['daily_sales'], true);
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'info'=>$info]);
    }

    /**
     * 修改年度报表
     * @return void
     */
    public function report_edit(){
        $id = I('id');
        $data = I('post.');
        $daily_sales = I('daily_sales/a', []);
        $data['daily_sales'] = json_encode($daily_sales);
        $this->check_edit_glrj($data['shop_id']);
        $model = D('Api/ShopSales');
        if($model->create($data)){
            $res = $model->where(['id'=>$id, 'user_id'=>$this->uid])->save();
            if($res !== false){
                $this->ajaxReturn(['s'=>true, 'm'=>'修改成功']);
            }else{
                $this->ajaxReturn(['s'=>false, 'm'=>'修改失败']);
            }
        }else{
            $this->ajaxReturn(['s'=>false, 'm'=>$model->getError()]);
        }
    }

    /**
     * 删除年度报表
     * @return void
     */
    public function report_del(){
        $ids = I('ids');
        $shop_id = I('shop_id');
        if(empty($ids)){
            $this->ajaxReturn(['s'=>false, 'm'=>'请选择删除项']);
        }
        $this->check_edit_glrj($shop_id);
        $res = D('Api/ShopSales')->where(['id'=>['in', $ids], 'shop_id'=>$shop_id])->delete();
        if($res!==false){
            $this->ajaxReturn(['s'=>true, 'm'=>'删除成功']);
        }else{
            $this->ajaxReturn(['s'=>false, 'm'=>'删除失败']);
        }
    }

    /**
     * 检测权限
     * @param    [type]     $shop_id 
     * @return   [type]              [description]
     */
    private function check_edit_glrj($shop_id)
    {
        $shopInfo = M('shop')->where(['id'=>$shop_id])->find();
        if(empty($shopInfo)){
            $this->ajaxReturn(['s'=>false, 'm'=>'棋牌室不存在']);
        }
        if(($this->uid && $shopInfo['uid']==$this->uid) || ($this->user && ($shopInfo['phone'] == $this->user['phone'] || $shopInfo['tel'] == $this->user['phone']))){

        }else{
            $hasStaff = M('shop_staff')->where(['shop_id'=>$shop_id, 'phone'=>$this->user['phone'], 'role'=>2])->find();
            if(empty($hasStaff)){
                $this->ajaxReturn(['s'=>false, 'm'=>'权限不足']);
            }
        }
    }

    public function glrj()
    {
        $customer_img = yzl_config('shop_glrj.shop_glrj_customer_img');
        $staff_img = yzl_config('shop_glrj.shop_glrj_staff_img');
        $report_img = yzl_config('shop_glrj.shop_glrj_sales_img');
        $develop_img = yzl_config('shop_glrj.shop_glrj_develop_img');
        $type_arr = [
            ['img'=>$customer_img, 'title'=>'客户管理'],
            ['img'=>$staff_img, 'title'=>'员工管理'],
            ['img'=>$report_img, 'title'=>'年度报表'],
            ['img'=>$develop_img, 'title'=>'开发中'],
        ];
        // 轮播
        $slider =  M('slider')->where(['type'=>6])->order('id asc')->field('id,img,link')->select();
        // 公告
        $notice = yzl_config('shop_glrj.shop_glrj_center_notice');
        $this->ajaxReturn(['s'=>true, 'category'=>$type_arr, 'slider'=>$slider, 'notice'=>$notice]);
    }
    

    public function vouchers()
    {
        $code = I('code');
        if(empty($code)){
            $this->ajaxReturn(['s'=>false, 'm'=>'参数不能为空']);
        }
        $info = M('vouchers')->where(['code'=>$code])->field('code,money,status')->find();
        if(empty($info)){
            $this->ajaxReturn(['s'=>false, 'm'=>'未查询到该券']); 
        }
        if($info['status']!=1){
            $this->ajaxReturn(['s'=>false, 'm'=>'该券已使用']);
        }
        unset($info['status']);
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'info'=>$info]);
    }

    /**
     * 抵扣优惠券
     */
    public function vouchers_use()
    {
        $code = I('code');
        if(empty($code)){
            $this->ajaxReturn(['s'=>false, 'm'=>'参数不能为空']);
        }
        $info = M('vouchers')->where(['code'=>$code])->field('code,money,status')->find();
        if(empty($info)){
            $this->ajaxReturn(['s'=>false, 'm'=>'未查询到该券']);
        }
        if($info['status']!=1){
            $this->ajaxReturn(['s'=>false, 'm'=>'该券已使用']);
        }
        unset($info['status']);
        $info['money'] = $info['money']*1;
        M('vouchers')->where(['code'=>$code])->save(['status'=>2, 'user_id'=>$this->uid, 'use_time'=>time()]);
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'd'=>$info]);
    }

    public function voucherInfo()
    {
        $code = I('code');
        if(empty($code)){
            $this->ajaxReturn(['s'=>false, 'm'=>'参数不能为空']);
        }
        $info = M('vouchers')->where(['code'=>$code])->field('code,money,status')->find();
        unset($info['status']);
        $info['money'] = $info['money']*1;
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'd'=>$info]);
    }

    public function vouchersUseList()
    {
        $list = M('vouchers')->where(['user_id'=>$this->uid])->order('use_time desc')->field('code,money,status')->select();
        $status_arr = ['2'=>'申请提现', '3'=>'申请提现中', '4'=>'已提现', '5'=>'提现失败'];
        foreach ($list as $key => &$row) {
            $row['status_name'] = isset($status_arr[$row['status']]) ? $status_arr[$row['status']] : '';
            $row['money'] = $row['money'] * 1;
        }
        $this->ajaxReturn(['s'=>true, 'm'=>'ok', 'list'=>$list]);
    }
}
